<template>
	<view class="baseForm">
		<view class="flex justify-between" style="padding: 0 15px; margin-bottom: 1px;padding-top: 3px;">
			<view @click="showPositionPicker" class="flex input-box">
				<u--input v-model="position" prefixIcon="search" border="none" placeholder="请选择位置" readonly
					class="input-self"></u--input>
				<image @click.stop="clearInfo()" v-show="position" src="@/static/image/delete.png" />
			</view>
			<u-button type="primary" icon="search" class="search-btn" @click="searchList"></u-button>
		</view>
		<!-- 搜索&扫码 -->
		<view class="upload-scan">
			<u-search v-model="searchText" shape="round" bgColor="#fff" :show-action="true" actionText="搜索"
				placeholder="请输入设备编号或名称" :animation="true" :clearabled="true" class="search" @search="searchList"
				@clear="clearList" @custom="searchList"></u-search>
			<u-icon name="scan" size="27px" :bold="false" @click="scanHandle"></u-icon>
		</view>
		<!-- tab-bar切换 -->
		<!-- <view class="tab-bar">
			<u-tabs
				:current="activeTab"
				:list="tabList"
				:scrollable="false"
				:activeStyle="{
					color: '#007aff',
					fontWeight: 'bold'
				}"
				lineWidth="34px"
				lineHeight="2px"
				lineColor="#007aff"
				@change="changeTab"
			></u-tabs>
		</view> -->

		<!-- 当前作业 -->
		<view class="activeHeight">
			<!-- 列表 -->
			<u-list ref="tableScroll" @scrolltolower="scrolltolower" class="list" v-if="total" :height="listHeight"
				lowerThreshold="50px" :pagingEnabled="true">
				<u-list-item v-for="(item, index) in tableList" :key="item.id" @click="jump(item)">
					<view class="card">
						<view class="flex record-title">
							<text class="line1">{{ item.assetName }}</text>
							<text>
								{{ item.assetCode }}
							</text>
						</view>
						<view class="flex flex-col justify-between flex-1 h-full record-content-body">
							<view class="record-content">
								<!-- <view class="record-item">
									<text>设备类型</text>
									<text>
										{{
											useDictionaryStore().filterDictName(
												"assetStatus",
												item.assetStatus
											)
										}}
									</text>
								</view> -->
								<view class="record-item" v-show="
										item.assetModelNo || item.assetBrandName
									">
									<text>品牌型号</text>
									<text class="">
										<text>{{ item.assetModelNo }}</text>
										<text v-if="item.assetModelNo">-</text>
										<text>{{ item.assetBrandName }}</text>
									</text>
								</view>
							</view>
						</view>
					</view>
				</u-list-item>
			</u-list>
			<view class="flex justify-center" v-show="tableLoading">
				<u-loading-icon color="#000a7b"></u-loading-icon>
			</view>
			<!-- 空数据 -->
			<view v-show="tableList.length === 0 && !tableLoading">
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>
		<!-- 树形选择器 -->
		<ba-tree-picker ref="positionPicker" :multiple="false" @select-change="positionChange" title="位置"
			:selectedData="showPositionValue" :localdata="positionList" valueKey="id" textKey="locationName"
			childrenKey="nodes" />
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, watch, onMounted } from "vue";
	import { onShow, onPullDownRefresh, onLoad } from "@dcloudio/uni-app";
	import { http } from "@/utils/http";
	import { PageResult, TabInfo } from "@/types/type";
	import { getSecondTime } from "@/utils/common";
	import { useDictionaryStore } from "@/stores/useDictionaryStore";
	import { useEamStore } from "@/stores/useEamStore";
	import BaTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue";
	import { toScanCode } from "@/components/hs-scancode/scan.js";
	// const activeTab = ref(0);
	// const tabList = [{ name: '所有' }, { name: '待处理' }, { name: '处理中' }, { name: '已完成' }];
	// function changeTab(val: TabInfo) {
	// 	activeTab.value = val.index;
	// 	searchList();
	// }
	
	const props = defineProps({
		isReturn: {
			type: String,
			default: "",
		},
	});
	
	// 选择位置信息
	const selectedPosition = computed(() =>
		JSON.parse(useEamStore().selectedPosition)
	);

	// 显示选择器
	const positionId = ref("");
	const position = ref("");
	const positionPicker = ref();
	function showPositionPicker() {
		positionPicker.value._show();
	}
	//监听选择（ids为数组）
	const showPositionValue = ref([]);
	function positionChange(ids, names) {
		console.log("ids", ids);
		positionId.value = ids[0] ?? "";
		position.value = names ?? "";
		showPositionValue.value = ids[0] ? [ids[0]] : [];
		useEamStore().setSelectedPosition({
			positionId: ids[0] ?? "",
			positionName: names ?? "",
		});
		
		setTimeout(()=>{
			searchList();
		}, 100)
	}

	// 清空数据
	function clearInfo() {
		positionId.value = "";
		position.value = "";
		useEamStore().setSelectedPosition({});
		showPositionValue.value = [];
		if (positionPicker.value?._reTreeList) {
			positionPicker.value._reTreeList();
		}
	}
	// 获取位置列表
	const positionList = ref();
	async function getPositionList() {
		const { data } = await http({
			method: "POST",
			url: `/eam/locationInfo/getTree`,
			data: {},
		});
		positionList.value = data;
	}

	// 待完成数据
	const tableList = ref([]);
	const tableLoading = ref(false);
	const current = ref(0);
	const totalPage = ref(0);
	const total = ref(0);

	//列表高度
	const listHeight = ref("");

	onLoad(() => {
		// #ifdef H5
		listHeight.value = "calc(100vh - 88px - 35px)";
		// #endif

		// #ifdef APP-PLUS
		listHeight.value = "calc(100vh - 48px - 35px)";
		// #endif

		if (selectedPosition.value?.positionId) {
			positionId.value = selectedPosition.value?.positionId;
			position.value = selectedPosition.value?.positionName;
			showPositionValue.value = [selectedPosition.value?.positionId];
		}

		loadmore();

		getPositionList();
	});

	onPullDownRefresh(() => {
		searchList();
	});

	async function loadmore(type ?: string) {
		try {
			current.value += 1;
			tableLoading.value = true;
			const result : PageResult<any> = await http({
				method: "POST",
				url: "/eam/equAssetInfo/queryByPage",
				data: {
					current: current.value,
					size: 20,
					data: {
						searchAssetInfo: searchText.value,
						locationId: positionId.value || "",
					},
				},
			}).finally(() => {
				tableLoading.value = false;
			});
			const list = result.data;
			for (let i = 0; i < list.length; i++) {
				tableList.value.push(list[i]);
			}
			totalPage.value = result.page;
			total.value = result.total;
			type === "refresh" && uni.stopPullDownRefresh();
		} catch (e) {
			console.log(e);
		}
	}
	const scrolltolower = () => {
		totalPage.value > current.value && loadmore();
	};

	// 点击扫码
	const searchText = ref("");
	// function openScan() {
	// 	/* #ifdef H5 */
	// 	uni.showToast({
	// 		icon: "none",
	// 		title: "请到安卓设备进行扫码",
	// 	});
	// 	/* #endif */
	// 	// 只允许通过相机扫码
	// 	uni.scanCode({
	// 		scanType: ["barCode", "qrCode"],
	// 		onlyFromCamera: true,
	// 		success: function (res) {
	// 			searchText.value = JSON.parse(JSON.stringify(res.result));
	// 			searchList();
	// 			console.log("条码类型：" + res.scanType);
	// 			console.log("条码内容：" + res.result);
	// 		},
	// 	});
	// }

	function scanHandle() {
		toScanCode({
			onlyFromCamera: true, // 只允许通过相机扫码
		})
			.then((res) => {
				uni.showToast({
					icon: "success",
					title: "扫码成功",
				});
				searchText.value = res;
				searchList();
			})
			.catch((e) => {
				uni.showToast({
					icon: "error",
					title: e,
				});
			});
	}

	// 列表搜索
	function searchList() {
		current.value = 0;
		tableList.value = [];
		loadmore("refresh");
	}

	function clearList() {
		searchText.value = "";
		searchList();
	}

	// 网页跳转
	async function jump(item) {
		const pages = getCurrentPages(); // 获取页面栈
		const currentPage = pages[pages.length - 1]; // 当前页面
		const prevPage = pages[pages.length - 2];    // 上一个页面

		if (prevPage && prevPage.route === 'pages/eam/equ/repairOrder/index' && !props.isReturn) {
			await useEamStore().setDeviceList(item);
			uni.navigateTo({
				url: '/pages/eam/equ/repairOrderCreate/index?assetKind=1&repairSource=1'
			});
		} else if (prevPage && prevPage.route === 'pages/eam/equ/pointInspection/index') {
			await useEamStore().setDeviceList(item);
			uni.navigateBack();
			// uni.navigateTo({
			// 	url: '/pages/eam/equ/pointInspection/components/pointInspectionCreate?assetKind=1&isRead=0'
			// });
		}else {
			await useEamStore().setDeviceList(item);
			uni.navigateBack();
		}
	}
</script>

<style lang="scss" scoped>
	uni-page-body {
		height: 100%;
		background-color: #fbfbff;
	}

	.search {
		:deep(.u-search__content) {
			box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
		}
	}

	.baseForm {
		background-color: #fbfbff;

		.tab-bar {
			padding: 0 20px;
		}

		.upload-scan {
			padding: $uni-page-padding;
			padding-top: 3px;
			padding-bottom: 3px;
			display: flex;
			align-items: center;

			// box-shadow: 0 1px 10px 0px rgb(19 10 236 / 10%);
			.u-icon {
				margin-left: 8px;
			}
		}

		.u-line {
			padding: 10px 0;
		}
	}

	.list {
		.card {
			margin: $uni-page-padding;
			margin-top: 5px;
			margin-bottom: 4px;
			border-radius: 7px;
			padding: 12px 20px 0px 20px;
			transition: all 300ms ease;
			border: 1px solid #efefef;
			background-color: #fff;

			.card-flex {
				display: flex;
				align-items: flex-start;
			}

			.right {
				flex: 1;
			}

			.title {
				font-size: 14px;
				line-height: 40px;
				height: 40px;
				margin-top: 8px;
				font-weight: bold;
				color: #101010;
				border-top: 1px solid #e5ebff;
			}

			.uni-btn {
				float: right;
				font-size: 12px;
				height: 24px;
				line-height: 24px;
				padding: 0 15px;
				margin-top: 7px;
				font-weight: 400;
			}

			.des {
				font-size: 12px;
				line-height: 20px;
				margin-bottom: 3px;
			}

			.left {
				flex-basis: calc(50% + 10px);
			}
		}
	}

	.record-title {
		display: flex;
		justify-content: space-between;
		margin: 2px 0 2px 0;
		color: $primary-color;

		uni-text:nth-child(1) {
			font-weight: bold;
			font-size: 15px;
		}

		uni-text:nth-child(2) {
			font-weight: bold;
			font-size: 15px;
			min-width: 60px;
			text-align: right;
		}
	}

	.record-item {
		margin: 7px 0 !important;
		color: #8f8e94 !important;
		word-break: break-all;
	}

	:deep(.input-box) {
		// width: calc(100% - 56px);
		width: 100%;
		// border: 0.5px solid #dadbde !important;
		border-radius: 100px;
		height: 32px;
		line-height: 32px;
		box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
		background-color: #fff;

		.u-input {
			pointer-events: none;
			height: 32px;
			line-height: 32px;
			padding-left: 10px !important;
		}

		.uni-input-placeholder {
			color: rgb(144, 147, 153) !important;
			font-size: 14px;
		}

		.u-icon__icon {
			font-size: 22px !important;
			line-height: 22px;
			font-weight: normal;
			top: 0px;
			color: rgb(144, 147, 153) !important;
		}

		image {
			padding: 6px 6px;
			width: 20px;
			height: 20px;
		}
	}

	:deep(.search-btn) {
		width: 32px;
		height: 34px;
		margin-left: 4px;
		border-radius: 4px;
		background-color: transparent;
		border: none;

		.u-icon__icon {
			margin-left: 5px;
			color: rgb(96, 98, 102) !important;
			font-size: 26px !important;
		}
	}
</style>